var _netModule = require('net');
var _mapModule = require('./mapModule.js');
var _parsingModule = require('./IRCParsing.js')

var port = 9988;

var mapIndex = 0;
var idListArray = 0;

var clients = new _mapModule.map();
var rooms = new _mapModule.map();

function Client(name, socket, roomKey, timePing, timePong, id) {
	this.id = id;
	this.name = name;
	this.socket = socket;
	this.roomKey = roomKey;
	this.timePing = timePing;
	this.timePoing = timePong;
}

function Room(roomName, userList) {
	this.roomName = roomName;
	this.userList = userList;
}

// var TCP_BUFFER_SIZE = Math.pow(2, 10);

var _netServer = _netModule.createServer(function(socket) {
	
	// var remoteAddress = socket.remoteAddress;
	// var remotePort = socket.remotePort;
// // 	
	// id = remoteAddress + ':' + remotePort;

	
	// buf = Buffer(TCP_BUFFER_SIZE);
	// console.log('buffersize:' + buf.length);

	// connect
	socket.on('connect', function() {
		socket.setMaxListeners(0);
		console.log('client connected... ip: ' + socket.remoteAddress + ' part: ' + socket.remotePort);
		
		socket.id = socket.remoteAddress + ':' + socket.remotePort;
		
		socket.write('connect success....\n');
		socket.write('create room....');

		
		// room search
		if (rooms.size() > 0) {
			console.log('roomList: ' + rooms.size());
			socket.write('join room: \n');
			
			var roomNamesArray = rooms.values();
			roomNamesArray.forEach(function(_roomObject) {
				// console.log('room List: ' + _roomList.roomName + '\n');
				socket.write('room name: ' + _roomObject.roomName + '\n');
			});

		}
		else{
			socket.write('room null');
		}
		
		
		// socket put
		var _tempStruct = new Client(socket.remoteAddress +':'+socket.remotePort , socket, null, new Date(), null, socket.remoteAddress +':'+socket.remotePort);
		clients.put(_tempStruct.id, _tempStruct);
		connectTime = _tempStruct.timePing.getHours()*60*60 + _tempStruct.timePing.getMinutes()*60 + _tempStruct.timePing.getSeconds() +'sec';
		
		console.log(':::::::::::::'+  _tempStruct.id + '         connect time: ' + _tempStruct.timePing);
		delete connectTime;
		_tempStruct.socket.setTimeout(600000);
		
				
	});
	
	
	
	socket.on('close', function() {
		console.log('close socket');
		// console.log( socket.remoteAddress);
		socket.emit('timeoutpong', clients.get(socket.id));
		console.log('LOG: [' + socket.id +'] is disconnected......');
		clients.remove(socket.id);
		
	});

	socket.on('end', function(data) {
		// console.log('end');
	});

	socket.on('drain', function(data) {
		// socket.resume();
		console.log('socket drain...');
	});

	socket.on('timeout', function() {
		
		
		var client = clients.get(socket.id);
		
		if( client == null) return;
		// if( client.socket != socket) return;
		
		console.log(client.name + '->>>>>>>>>> timetout!!!!!!!');
		
		client.socket.write('/quit');
		clients.remove(socket.id);
		
		if (client.roomKey == null) return;
		
		var room = rooms.get(client.roomKey);
		if( room != null)
		{
			room.userList.remove(socket.id);	
			
			if( room.userList.size() <= 0 )
			{
				rooms.remove(client.roomKey);
			}
		
		}
		
		
		

	});
	
	socket.on('timeoutpong', function(client){
		
		client.timePong = new Date();
		
		connectTime = client.timePong.getHours()*60*60 + client.timePong.getMinutes()*60 + client.timePong.getSeconds();
		originTime =  client.timePing.getHours()*60*60 + client.timePing.getMinutes()*60 + client.timePing.getSeconds();
		
		client.timePing = new Date();
		
		console.log( client.name + '<- pong time: ' + client.timePong + 'sec        ' + 'waitTime: ' + ( connectTime.valueOf() - originTime.valueOf()) + ' sec');
		delete connectTime;
		delete originTime;
	})

	//data send
	socket.on('data', function(data) {
		console.log(data);
		var client = clients.get(socket.remoteAddress + ':' + socket.remotePort);
		// if( client.socket != socket) return;
		_parsingModule.ParsingDataToIRC(data, client, socket, rooms);
		
	});

}).listen(port, function() {
	console.log('server listing...');
});


// key input & send message
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
	SendMessageToClient(chunk);
});

//send to client
var SendMessageToClient = function(message) {
	var sender = this;
	
	var allClients = clients.values();
	
	allClients.forEach(function(client){
		// console.log('message test: '+ message.toString().substr(0, _tempClient._name.toString().length) );
		var isClientSocket = (client.socket != sender);
		if (isClientSocket) {
			client.socket.write('Server: ' + message.toString().replace(/(\s*$)/gi, '') );
		}
	});
}

// user count check;
setInterval(function() {
	// console.log('Connection count:' + _netServer.connections);
	// console.log('clientArray Lenghth:' + _clientsArray.length);

	// _clientsArray.forEach(function(clinetObject){
	// clinetObject._socket.setTimeout(2000);
	// });

}, 3000);

